<script setup lang="ts">
import '@wangeditor/editor/dist/css/style.css';
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import {nextTick, onBeforeUnmount, onMounted, ref, shallowRef, watch} from "vue";

const emit = defineEmits<{ (e: 'updateContent', content: string): void }>()

const editorRef = shallowRef()
const valueHtml = ref('')
const mode = ref("default")
const toolbarConfig = {}
const editorConfig = { placeholder: '请输入内容...' }

const props = defineProps({
  content: {
    type: String,
    default: "请输入内容..."
  }
})


const handleChange = () => {
  valueHtml.value  = editorRef.value.getHtml()
  emit('updateContent', valueHtml.value)
}

watch(() => props.content, (newContent) => {
  nextTick(() => {
    if (editorRef.value) {
      // console.log(" 当前编辑器的状态：", editorRef.value);
      // 富文本编辑器按 html 格式回显
      editorRef.value.setHtml(newContent)
      valueHtml.value = newContent
    }
  })
})

const handleCreated = (editor) => {
  editorRef.value = editor // 记录 editor 实例，重要！
}


onMounted(async() => {
  await nextTick(); // 延迟渲染，确保 DOM 更新完成
  if(props.content) {
    valueHtml.value = props.content
  }
})


// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value
  if (editor == null) return
  editor.destroy()
})
</script>

<template>
  <div style="border: 1px solid #ccc; margin-top: 10px">
    <Toolbar
        style="border-bottom: 1px solid #ccc"
        :editor="editorRef"
        :defaultConfig="toolbarConfig"
        :mode="mode"
    />
    <Editor
        style="width: 100%; height: 500px; overflow-y: hidden;"
        v-model="valueHtml"
        :defaultConfig="editorConfig"
        :mode="mode"
        @onCreated="handleCreated"
        @onChange="handleChange"
    />
  </div>
</template>

<style scoped>

</style>